<?php
/*
 * 快递100API
 */
namespace kuaidi100;

use app\common\model\System;

class Kuaidi
{
    //智能识别单号
    public static function autonumber($num)
    {
        $exp = System::get_config_by_code('express');
        //单号智能识别
        $param = array();
        $post_data = [
            'key' => $exp['exp_key'],
            'num' => $num
        ];
        $url = 'http://www.kuaidi100.com/autonumber/auto';    //智能判断请求地址
        $post_data = self::url_encode($post_data);

        $result = https_request($url, $post_data);
        return json_to_array($result);
    }
    //实时查询
    public static function synquery($num)
    {
        $exp = System::get_config_by_code('express');
        $data = self::autonumber($num);
        //物流轨迹
        $key = $exp['exp_key'];           //客户授权key
        $customer = $exp['exp_customer']; //查询公司编号
        $param = [
            'com' => $data[0]['comCode'], //快递公司编码
            'num' => $num,                //快递单号
            'phone' => '',                //手机号
            'from' => '',                 //出发地城市
            'to' => '',                   //目的地城市
            'resultv2' => '1'             //开启行政区域解析
        ];
        
        //请求参数
        $post_data = array();
        $post_data["customer"] = $customer;
        $post_data["param"] = json_encode($param);
        $sign = md5($post_data["param"].$key.$post_data["customer"]);
        $post_data["sign"] = strtoupper($sign);

        $post_data = self::url_encode($post_data);
        $url = 'http://poll.kuaidi100.com/poll/query.do';    //实时查询请求地址

        $result = https_request($url, $post_data);
        $post_data = json_to_array($result);
        $post_data['name'] = $data[0]['name'];
        return $post_data;
    }
    //地图轨迹
    public static function map($num)
    {
        $exp = System::get_config_by_code('express');
        $data = self::autonumber($num);
        //参数设置
        $key = $exp['exp_key'];           //客户授权key
        $customer = $exp['exp_customer']; //查询公司编号
        $param = array (
            'com' => $data[0]['comCode'], //快递公司编码
            'num' => $num,                //快递单号
            'phone' => '',                //手机号
            'from' => '',                 //出发地信息
            'to' => '',                   //目的地信息
            'show' => '0',                //返回格式：0：json格式（默认），1：xml，2：html，3：text
            'order' => 'desc',            //返回结果排序:desc降序（默认）,asc 升序
            'orderTime' => ''             //订单下单时间，格式为（yyyy-MM-dd HH:mm:ss）如：2020-12-16 12:59:59
        );
        
        //请求参数
        $post_data = array();
        $post_data["customer"] = $customer;
        $post_data["param"] = json_encode($param);
        $sign = md5($post_data["param"].$key.$post_data["customer"]);
        $post_data["sign"] = strtoupper($sign);
        
        $url = 'http://poll.kuaidi100.com/poll/maptrack.do';    //地图轨迹请求地址
        $post_data = self::url_encode($post_data);

        //发送post请求
        $result = https_request($url, $post_data);
        return json_to_array($result);
    }
    //短信请求
    public static function sms()
    {
        $exp = System::get_config_by_code('express');
        //参数设置
        $key = $exp['exp_key'];           //客户授权key
        $userid = '';         //短信接口用户ID
        $seller = '';         //商户名称签名
        $phone = '';          //接收短信手机号
        $tid = 0;             //短信模板ID
        $content = array (
            '验证码' => '256988',
            'remark' => '（若非本人操作请忽略）'
        );                     //短信模板替换内容
        $outorder = '';        //外部订单号
        $callback = '';        //短信状态回调地址
        
        $sign = strtoupper(md5($key.$userid));

        //请求参数
        $post_data = array();
        $post_data["sign"] = $sign;
        $post_data["userid"] = $userid;
        $post_data["seller"] = $seller;
        $post_data["phone"] = $phone;
        $post_data["tid"] = $tid;
        $post_data["content"] = json_encode($content);
        $post_data["outorder"] = $outorder;
        $post_data["callback"] = $callback;

        $url = 'http://apisms.kuaidi100.com:9502/sms/send.do';    //发送短信请求地址
        
        $post_data = self::url_encode($post_data);
        //发送post请求
        $result = https_request($url, $post_data);
        return json_to_array($result);
    }

    //电子面单
    public static function ele_img()
    {
        $exp = System::get_config_by_code('express');
        //参数设置
        $key = $exp['exp_key'];           //客户授权key
        $secret = '';                     //授权secret
        list($msec, $sec) = explode(' ', microtime());
        $t = (float)sprintf('%.0f', (floatval($msec) + floatval($sec)) * 1000);    //当前时间戳
        $param = array (
            'type' => '10',                    //业务类型，默认为10
            'partnerId' => '',                 //电子面单客户账户或月结账号
            'partnerKey' => '',                //电子面单密码
            'net' => '',                       //收件网点名称,由快递公司当地网点分配
            'kuaidicom' => '',                 //快递公司的编码
            'recManName' => '',                //收件人姓名
            'recManMobile' => '',              //收件人手机
            'recManPrintAddr' => '',           //收件人地址
            'sendManName' => '',               //寄件人姓名
            'sendManMobile' => '',             //寄件人手机
            'sendManPrintAddr' => '',          //寄件人地址
            'tempid' => '',                    //电子面单模板编码
            'cargo' => '',                     //物品名称
            'count' => '',                     //物品总数量
            'weight' => '',                    //物品总重量
            'payType' => 'SHIPPER',            //支付方式
            'expType' => '标准快递',           //快递类型: 标准快递（默认）、顺丰特惠、EMS经济
            'remark' => ''                     //备注
        );
        
        //请求参数
        $post_data = array();
        $post_data["param"] = json_encode($param, JSON_UNESCAPED_UNICODE);
        $post_data["key"] = $key;
        $post_data["t"] = $t;
        $sign = md5($post_data["param"].$t.$key.$secret);
        $post_data["sign"] = strtoupper($sign);
        
        $url = 'http://poll.kuaidi100.com/printapi/printtask.do?method=getPrintImg';    //电子面单请求地址
        //发送post请求
        $result = https_request($url, $post_data);
        return json_to_array($result);
    }
    //电子面单返回html内容
    public static function ele_html($num)
    {
        $exp = System::get_config_by_code('express');
        //参数设置
        $key = $exp['exp_key'];           //客户授权key
        $secret = '';                     //授权secret
        list($msec, $sec) = explode(' ', microtime());
        $t = (float)sprintf('%.0f', (floatval($msec) + floatval($sec)) * 1000);    //当前时间戳
        $param = array (
            'partnerId' => '',                 //电子面单客户账户或月结账号
            'partnerKey' => '',                //电子面单密码
            'net' => '',                       //收件网点名称,由快递公司当地网点分配
            'kuaidicom' => '',                 //快递公司的编码
            'recMan' => array (
                'name' => '',                  //收件人姓名
                'mobile' => '',                //收件人手机
                'printAddr' => '',             //收件人地址
                'company' => ''                //收件人公司名
            ),
            'sendMan' => array (
                'name' => '',                  //寄件人姓名
                'mobile' => '',                //寄件人手机
                'printAddr' => '',             //寄件人地址
                'company' => ''                //寄件人公司名
            ),
            'cargo' => '',                     //物品名称
            'count' => '',                     //物品总数量
            'weight' => '',                    //物品总重量
            'payType' => 'SHIPPER',            //支付方式
            'expType' => '标准快递',           //快递类型: 标准快递（默认）、顺丰特惠、EMS经济
            'remark' => '',                    //备注
            'needTemplate' => '1'              //是否返回面单：0：不开启(默认)、1：开启
        );
        
        //请求参数
        $post_data = array();
        $post_data["param"] = json_encode($param, JSON_UNESCAPED_UNICODE);
        $post_data["key"] = $key;
        $post_data["t"] = $t;
        $sign = md5($post_data["param"].$t.$key.$secret);
        $post_data["sign"] = strtoupper($sign);
        
        $url = 'http://poll.kuaidi100.com/eorderapi.do?method=getElecOrder';    //电子打印请求地址
        //发送post请求
        $result = https_request($url, $post_data);
        return json_to_array($result);

    }
    //电子面单打印
    public static function ele_print($num)
    {
        $exp = System::get_config_by_code('express');
        //参数设置
        $key = $exp['exp_key'];           //客户授权key
        $secret = '';                     //授权secret
        list($msec, $sec) = explode(' ', microtime());
        $t = (float)sprintf('%.0f', (floatval($msec) + floatval($sec)) * 1000);    //当前时间戳
        $param = array (
            'type' => '10',                    //业务类型，默认为10
            'partnerId' => '',                 //电子面单客户账户或月结账号
            'partnerKey' => '',                //电子面单密码
            'net' => '',                       //收件网点名称,由快递公司当地网点分配
            'kuaidicom' => '',                 //快递公司的编码
            'recMan' => array (
                'name' => '',                  //收件人姓名
                'mobile' => '',                //收件人手机
                'printAddr' => '',             //收件人地址
                'company' => ''                //收件人公司名
            ),
            'sendMan' => array (
                'name' => '',                  //寄件人姓名
                'mobile' => '',                //寄件人手机
                'printAddr' => '',             //寄件人地址
                'company' => ''                //寄件人公司名
            ),
            'cargo' => '',                     //物品名称
            'count' => '',                     //物品总数量
            'weight' => '',                    //物品总重量
            'payType' => 'SHIPPER',            //支付方式
            'expType' => '标准快递',           //快递类型: 标准快递（默认）、顺丰特惠、EMS经济
            'remark' => '',                    //备注
            'tempid' => '',                    //电子面单模板编码
            'siid' => ''                       //设备编码
        );

        //请求参数
        $post_data = array();
        $post_data["param"] = json_encode($param, JSON_UNESCAPED_UNICODE);
        $post_data["key"] = $key;
        $post_data["t"] = $t;
        $sign = md5($post_data["param"].$t.$key.$secret);
        $post_data["sign"] = strtoupper($sign);

        $url = 'http://poll.kuaidi100.com/printapi/printtask.do?method=eOrder';    //电子面单打印请求地址
        //发送post请求
        $result = https_request($url, $post_data);
        return json_to_array($result);
    }
    //商家寄件获取取件码
    public static function bsent_code($num)
    {

        $exp = System::get_config_by_code('express');
        //参数设置
        $key = $exp['exp_key'];           //客户授权key
        $secret = '';         //客户授权secret
        $param = array (
            'taskId' => '',            //任务ID
            'orderId' => ''            //订单ID
        );
        $param_str = json_encode($param, JSON_UNESCAPED_UNICODE);
        list($msec, $sec) = explode(' ', microtime());
        $t = (float)sprintf('%.0f', (floatval($msec) + floatval($sec)) * 1000);    //当前时间戳
        $sign = strtoupper(md5($param_str.$t.$key.$secret));

        //请求参数
        $post_data = array();
        $post_data["method"] = 'getCode';
        $post_data["key"] = $key;
        $post_data["t"] = $t;
        $post_data["sign"] = $sign;
        $post_data["param"] = $param_str;

        $url = 'http://order.kuaidi100.com/order/borderbestapi.do';    //商家寄件
        //发送post请求
        $result = https_request($url, $post_data);
        return json_to_array($result);
        
    }
    //商家寄件取消
    public static function bsent_cancel($num)
    {
        $exp = System::get_config_by_code('express');
        //参数设置
        $key = $exp['exp_key'];           //客户授权key
        $secret = '';         //客户授权secret
        $param = array (
            'taskId' => '',            //任务ID
            'orderId' => '',           //订单ID
            'cancelMsg' => ''          //取消原因
        );
        $param_str = json_encode($param, JSON_UNESCAPED_UNICODE);
        list($msec, $sec) = explode(' ', microtime());
        $t = (float)sprintf('%.0f', (floatval($msec) + floatval($sec)) * 1000);    //当前时间戳
        $sign = strtoupper(md5($param_str.$t.$key.$secret));

        //请求参数
        $post_data = array();
        $post_data["method"] = 'cancelBest';
        $post_data["key"] = $key;
        $post_data["t"] = $t;
        $post_data["sign"] = $sign;
        $post_data["param"] = $param_str;

        $url = 'http://order.kuaidi100.com/order/borderbestapi.do';    //商家寄件
        //发送post请求
        $result = https_request($url, $post_data);
        return json_to_array($result);
        
    }
    //商家寄件下单
    public static function bsent_order($num)
    {
        $exp = System::get_config_by_code('express');
        //参数设置
        $key = $exp['exp_key'];             //客户授权key
        $secret = '';                       //客户授权secret
        $param = array (
            'kuaidicom' => '',              //快递公司的编码
            'recManName' => '',             //收件人姓名
            'recManMobile' => '',           //收件人手机号
            'recManPrintAddr' => '',        //收件人所在完整地址
            'sendManName' => '',            //寄件人姓名
            'sendManMobile' => '',          //寄件人的手机号
            'sendManPrintAddr' => '',       //寄件人所在的完整地址
            'callBackUrl' => '',            //callBackUrl订单信息回调
            'cargo' => '',                  //物品名称
            'weight' => '1',                //物品总重量KG
            'serviceType' => '标准快递',    //快递业务服务类型
            'remark' => '',                 //备注
            'salt' => ''                    //签名用随机字符串
        );
        $param_str = json_encode($param, JSON_UNESCAPED_UNICODE);
        list($msec, $sec) = explode(' ', microtime());
        $t = (float)sprintf('%.0f', (floatval($msec) + floatval($sec)) * 1000);    //当前时间戳
        $sign = strtoupper(md5($param_str.$t.$key.$secret));

        //请求参数
        $post_data = array();
        $post_data["method"] = 'bOrderBest';
        $post_data["key"] = $key;
        $post_data["t"] = $t;
        $post_data["sign"] = $sign;
        $post_data["param"] = $param_str;

        $url = 'http://order.kuaidi100.com/order/borderbestapi.do';    //商家寄件
        //发送post请求
        $result = https_request($url, $post_data);
        return json_to_array($result);
        
    }
    //商家寄件获取运力
    public static function bsent_querymkt($num)
    {
        $exp = System::get_config_by_code('express');
        //参数设置
        $key = $exp['exp_key'];           //客户授权key
        $secret = '';         //客户授权secret
        $param = array (
            'sendAddr' => '广东省深圳市南山区软件产业基地4栋C座10G'      //寄件人所在的完整地址，可通过：https://api.kuaidi100.com/product/expressprice 查找运力覆盖范围
        );
        $param_str = json_encode($param, JSON_UNESCAPED_UNICODE);
        list($msec, $sec) = explode(' ', microtime());
        $t = (float)sprintf('%.0f', (floatval($msec) + floatval($sec)) * 1000);    //当前时间戳
        $sign = strtoupper(md5($param_str.$t.$key.$secret));

        //请求参数
        $post_data = array();
        $post_data["method"] = 'querymkt';
        $post_data["key"] = $key;
        $post_data["t"] = $t;
        $post_data["sign"] = $sign;
        $post_data["param"] = $param_str;

        $url = 'http://order.kuaidi100.com/order/borderbestapi.do';    //商家寄件
        //发送post请求
        $result = https_request($url, $post_data);
        return json_to_array($result);
    }
    //订阅请求
    public static function subscribe($num)
    {
        $exp = System::get_config_by_code('express');
        $data = self::autonumber($num);
        //参数设置
        $key = $exp['exp_key'];           //客户授权key
        $param = array (
            'company' => $data[0]['comCode'], //快递公司编码
            'number' => $num,                //快递单号
            'from' => '',                     //出发地城市
            'to' => '',                       //目的地城市
            'key' => $key,                    //客户授权key
            'parameters' => array (
                'callbackurl' => '',          //回调地址
                'salt' => '',                 //加密串
                'resultv2' => '1',            //行政区域解析
                'autoCom' => '0',             //单号智能识别
                'interCom' => '0',            //开启国际版
                'departureCountry' => '',     //出发国
                'departureCom' => '',         //出发国快递公司编码
                'destinationCountry' => '',   //目的国
                'destinationCom' => '',       //目的国快递公司编码
                'phone' => ''                 //手机号
            )
        );
        //请求参数
        $post_data = array();
        $post_data["schema"] = 'json';
        $post_data["param"] = json_encode($param);
        
        $url = 'http://poll.kuaidi100.com/poll';    //订阅请求地址
        $post_data = self::url_encode($post_data);
        //发送post请求
        $result = https_request($url, $post_data);
        return json_to_array($result);
    }
    //字符编码
    private static function url_encode($post_data)
    {
        $params = "";
        foreach ($post_data as $k=>$v) {
            $params .= "$k=".urlencode($v)."&";     //默认UTF-8编码格式
        }
        return substr($params, 0, -1);
    }


}
